package com.sindvision.cces.controller;

import com.sindvision.cces.beans.User;
import com.sindvision.cces.http.GeneralException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: chenjintao
 * @Date: 2019-11-22 18:33
 */
@RestController
@RequestMapping("/user")
@Api(value = "/user", description = "用户接口")
public class UserController {

    @PostMapping("/login")
    @ApiOperation("新增一个元数据字段")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", required = true),
            @ApiImplicitParam(name = "password", value = "密码", required = true),
    })
    public Object login(@RequestParam("username") String username,
                        @RequestParam("password") String password) throws GeneralException {
        if (StringUtils.isEmpty(username)) {
            throw new GeneralException("请输入用户名");
        }
        if (StringUtils.isEmpty(password)) {
            throw new GeneralException("请输入密码");
        }
        Subject currentUser = SecurityUtils.getSubject();

        try {
            if (!currentUser.isAuthenticated()) {
                UsernamePasswordToken token = new UsernamePasswordToken(username, password);
                currentUser.login(token);
            }
        } catch (Exception e) {
            if (e instanceof UnknownAccountException || e instanceof IncorrectCredentialsException) {
                throw new GeneralException("账号或密码错误");
            } else {
                throw new GeneralException("系统错误");
            }
        }

        User user = (User) currentUser.getSession().getAttribute(User.SESSION_ATTR_NAME);
        if (user.getStatus() == 1) {
            SecurityUtils.getSubject().logout();
            throw new GeneralException("账号被禁用");
        }
        if (user.getDelTag() == 1) {
            SecurityUtils.getSubject().logout();
            throw new GeneralException("账号不存在");
        }

        return user;
    }

    @ApiOperation("退出登录")
    @GetMapping("/logout")
    @RequiresAuthentication
    public Object logout() {
        SecurityUtils.getSubject().logout();
        return "success";
    }

    @PostMapping("/test/check/login")
    @RequiresAuthentication
    public Object testCheckLogin() {
        return "OK";
    }

}
